package com.tnxst.phexamination.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.github.gcacace.signaturepad.views.SignaturePad;
import com.tnxst.phexamination.R;
import com.tnxst.phexamination.view.GlideEngine;
import com.tnxst.phexamination.viewmodel.GlobalViewModel;

import org.apache.commons.collections.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class Utils {
    public static void Toast(Context context, String str) {
        Toast.makeText(context, str, Toast.LENGTH_LONG).show();
    }

    public static void setHint(View v, boolean hasFocus) {
        EditText textView = (EditText) v;
        String hint = null;
        if (hasFocus) {
            hint = textView.getHint().toString();
            textView.setTag(hint);
            textView.setHint("");
        } else {
            hint = v.getTag().toString();
            textView.setHint(hint);
        }
    }

    public static String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    public static Date setTime(String str) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                date = format.parse(str);
            } catch (ParseException parseException) {
                parseException.printStackTrace();
            }
        }
        return date;
    }

    public static String getStringFromDate(Date date) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return f.format(date);
    }

    public static Date getDateFromString(String str) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = null;
        try {
            parse = f.parse(str);
        } catch (ParseException e) {
            f = new SimpleDateFormat("yyyy-MM-dd");
            try {
                parse = f.parse(str);
            } catch (ParseException parseException) {
                parseException.printStackTrace();
            }
        }
        return parse;
    }

    public static void loadChatImage(final Context mContext, String imgUrl, final ImageView imageView) {
        if (StringUtils.isNull(imgUrl))
            return;
        Glide.with(mContext)
                .load(imgUrl) // 图片地址
                .into(imageView);
    }

    public static void loadChatImage(final Context mContext, Drawable drawable, final ImageView imageView) {
        if (StringUtils.isNull(drawable))
            return;
        Glide.with(mContext)
                .load(drawable) // 图片地址
                .into(imageView);
    }

    private static final int invalidAge = -1;//非法的年龄，用于处理异常。
    /**
     * @param idNumber 身份证
     * @return age
     */
    public static Integer getAge(String idNumber) throws ParseException {
        String dateStr;
        if (idNumber.length() == 15) {
            dateStr = "19" + idNumber.substring(6, 12);
        } else if (idNumber.length() == 18) {
            dateStr = idNumber.substring(6, 14);
        } else {//默认是合法身份证号，但不排除有意外发生
            return invalidAge;
        }


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        try {
            Date birthday = simpleDateFormat.parse(dateStr);
            return getAgeByDate(birthday);
        } catch (ParseException e) {
            return invalidAge;
        }

    }
    public static int getAgeByDate(Date birthday) {
        Calendar calendar = Calendar.getInstance();
        //calendar.before()有的点bug
        if (calendar.getTimeInMillis() - birthday.getTime() < 0L) {
            return invalidAge;
        }
        int yearNow = calendar.get(Calendar.YEAR);
        int monthNow = calendar.get(Calendar.MONTH);
        int dayOfMonthNow = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.setTime(birthday);
        int yearBirthday = calendar.get(Calendar.YEAR);
        int monthBirthday = calendar.get(Calendar.MONTH);
        int dayOfMonthBirthday = calendar.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirthday;
        if (monthNow <= monthBirthday && monthNow == monthBirthday && dayOfMonthNow < dayOfMonthBirthday || monthNow < monthBirthday) {
            age--;
        }
        return age;
    }
    public static Date addTime(Date date, int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, year);
        calendar.add(Calendar.MONTH, month);
        calendar.add(Calendar.DAY_OF_YEAR, day);
        return calendar.getTime();
    }

    /**
     * 分割包含,的字符串
     * @param str
     * @return
     */
    public static String[] divisionString(String str){
        if (StringUtils.isNull(str))
            return null;
        if (str.contains(",")){
            String[] split = str.split(",");
            return split;
        }
        return new String[]{str};
    }


    /**
     * 合并成含,的字符串
     * @param strings
     * @return
     */
    public static String mergeString(List<String> strings){
        if (CollectionUtils.isEmpty(strings))
            return "";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < strings.size(); i++) {
            String string = strings.get(i);
            if (i == strings.size() - 1)
                buffer.append(string);
            else
                buffer.append(string).append(",");
        }
        return buffer.toString();
    }

    public static List<Integer> divisionBinary(Integer symptom){
        List<Integer> result = new ArrayList<>();
        if (symptom == 0){
            result.add(0);
            return result;
        }
        String s = Integer.toBinaryString(symptom);
        char[] chars = s.toCharArray();
        int k = 1;
        for (int i = chars.length - 1; 0 <= i; i--) {
            char c = chars[i];
            if (c == '0'){
                k++;
                continue;
            }
            result.add(k);
            k++;
        }
        return result;
    }

    public static void saveSignature(Activity activity, Button button){
        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity);
        View view = View.inflate(activity, R.layout.handwritten_signature_layout, null);
        alertDialog
                .setView(view)
                .create();
        final AlertDialog show = alertDialog.show();
        Button save = view.findViewById(R.id.save);
        Button clear = view.findViewById(R.id.clear);
        Button back = view.findViewById(R.id.back);
        SignaturePad signaturePad = view.findViewById(R.id.signaturePad);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signaturePad.clear();
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show.dismiss();
            }
        });

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap signatureBitmap = signaturePad.getSignatureBitmap();
                File directory = Environment.getExternalStorageDirectory();
                File photo = new File(directory.getPath() + File.separator + "Phexamination" + File.separator + "Picture" + File.separator + "IMG_HSL_"+ System.currentTimeMillis()+".jpg");
                if (addJpgSignatureToGallery(signatureBitmap,photo)){
                    signaturePad.clear();
                    button.setHint(photo.getPath());
                    button.setText("已签名");
                }
                show.dismiss();
            }
        });
    }

//    public static void saveSignature(Activity activity, GlobalViewModel viewModel){
//        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity);
//        View view = View.inflate(activity, R.layout.handwritten_signature_layout, null);
//        alertDialog
//                .setView(view)
//                .create();
//        final AlertDialog show = alertDialog.show();
//        Button save = view.findViewById(R.id.save);
//        Button clear = view.findViewById(R.id.clear);
//        Button back = view.findViewById(R.id.back);
//        SignaturePad signaturePad = view.findViewById(R.id.signaturePad);
//        clear.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                signaturePad.clear();
//            }
//        });
//        back.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                show.dismiss();
//            }
//        });
//
//        save.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Bitmap signatureBitmap = signaturePad.getSignatureBitmap();
//                File directory = Environment.getExternalStorageDirectory();
//                File photo = new File(directory.getPath() + File.separator + "IMG_HSL_"+ System.currentTimeMillis()+".jpg");
//                if (addJpgSignatureToGallery(signatureBitmap,photo)){
//                    signaturePad.clear();
//                    viewModel.setDoctorSignature(photo.getPath());
//                }
//                com.tiannanxints.phexamination.utils.Utils.Toast(activity,"保存成功！");
//                show.dismiss();
//            }
//        });
//    }

    public static boolean addJpgSignatureToGallery(Bitmap signature, File photo) {
        boolean result = false;
        try {
            saveBitmapToJPG(signature, photo);
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    public static void saveBitmapToJPG(Bitmap bitmap, File photo) throws IOException {
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmap, 0, 0, null);
        OutputStream stream = new FileOutputStream(photo);
        newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
        stream.close();
    }

//    public static void showImage(Activity activity, String url){
//        File file = new File(url);
//        if (!(file.exists() && file.isFile()))
//            return;
//        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity);
//        View view = View.inflate(activity, R.layout.show_image, null);
//        alertDialog
//                .setView(view)
//                .create();
//        final AlertDialog show = alertDialog.show();
//        ImageView imageView = show.findViewById(R.id.show);
//        GlideEngine.createGlideEngine().loadImage(activity,url,imageView);
//        imageView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                show.dismiss();
//            }
//        });
//    }
}